package com.example.skillcinema.ui.screens.main

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.isVisible
import androidx.fragment.app.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.navigation.fragment.findNavController
import androidx.paging.LoadState
import com.example.skillcinema.R
import com.example.skillcinema.adapters.FilmAllPagedAdapter
import com.example.skillcinema.adapters.FootLoadStateAdapter
import com.example.skillcinema.adapters.StaffFilmographyPagedAdapter
import com.example.skillcinema.adapters.StaffFilmographyRecyclerViewAdapter
import com.example.skillcinema.databinding.FragmentStaffDetailBinding
import com.example.skillcinema.databinding.FragmentStaffFilmographyBinding
import com.example.skillcinema.db.displaymodels.FilmDisplayModel
import com.example.skillcinema.db.models.Episode
import com.example.skillcinema.ui.screens.main.viewmodels.StaffDetailViewModel
import com.example.skillcinema.ui.screens.main.viewmodels.StaffFilmographyViewModel
import com.google.android.material.chip.Chip
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import kotlin.getValue

@AndroidEntryPoint
class StaffFilmographyFragment : Fragment() {
    private var _binding: FragmentStaffFilmographyBinding? = null
    private val binding: FragmentStaffFilmographyBinding
        get() = _binding!!
    private val viewModel: StaffFilmographyViewModel by viewModels<StaffFilmographyViewModel>()
    private var staffId: Int = 0
    private var staffName: String = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        arguments?.let {
            staffId = it.getInt(STAFF_ID_ARG)
            staffName = it.getString(STAFF_NAME_ARG) ?: ""
            viewModel.id = staffId
            viewModel.loadData()
        }
    }

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?
    ): View? {
        _binding = FragmentStaffFilmographyBinding.inflate(inflater, container, false)
        return binding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        (activity as? AppCompatActivity)?.setSupportActionBar(binding.toolbar)
        (activity as? AppCompatActivity)?.supportActionBar?.setDisplayHomeAsUpEnabled(true)
        (activity as? AppCompatActivity)?.supportActionBar?.setDisplayShowTitleEnabled(false)
        binding.toolbar.title = ""
        binding.toolbar.setNavigationOnClickListener {
            findNavController().navigateUp()
        }
        val adapter: StaffFilmographyPagedAdapter =
            StaffFilmographyPagedAdapter { id -> filmClicked(id) }
        binding.staffNameTextView.text = staffName
        binding.filmographyRecyclerView.adapter = adapter.withLoadStateFooter(
            FootLoadStateAdapter()
        )
        binding.swipeRefresh.setOnRefreshListener {
            adapter.refresh()
        }
        adapter.loadStateFlow.onEach {
            binding.swipeRefresh.isRefreshing = it.refresh == LoadState.Loading
        }.launchIn(lifecycleScope)
        lifecycleScope.run {
            launch {
                viewModel.staffFilmographyKeyFlow.collect {
                    if (it.isNotEmpty()) viewModel.setCurrentKey(it.first())
                    it.forEachIndexed { index, item ->
                        val chip: Chip = View.inflate(
                            binding.seasonChipGroup.context, R.layout.season_chip, null
                        ) as Chip
                        chip.text = item
                        if (index == 0) chip.isChecked = true
                        chip.setOnClickListener {
                            viewModel.setCurrentKey(item)
                        }
                        binding.seasonChipGroup.addView(chip)
                    }
                }
            }
            launch {
                viewModel.filmPaged.collectLatest {
                    adapter.submitData(it)
                }
            }
        }
    }

    private fun filmClicked(id: Int) {
        val bundle: Bundle = Bundle().apply {
            putInt(FilmDetailsFragment.FILM_ID_ARG, id)
        }
        findNavController().navigate(
            R.id.action_staffFilmographyFragment_to_filmDetailsFragment, bundle
        )
    }

    override fun onDestroyView() {
        super.onDestroyView()
        _binding = null
    }

    companion object {
        @JvmStatic
        fun newInstance(param1: Int, param2: String) = StaffDetailFragment().apply {
            arguments = Bundle().apply {
                putInt(STAFF_ID_ARG, param1)
                putString(STAFF_NAME_ARG, param2)
            }
        }

        const val STAFF_ID_ARG = "staff_id"
        const val STAFF_NAME_ARG = "staff_name"
    }
}